package com.calt.plm.basic.core.action;

import com.calt.plm.basic.core.annoation.BusinessAction;
import com.calt.plm.basic.core.context.EntityContext;
import com.calt.plm.basic.core.entity.AbstractActionEntity;
import com.calt.plm.basic.core.service.EntityQueryService;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

@BusinessAction(name = "lifeCycle")
public interface LifeCycleI extends VersionI
{
    String BIZ_ID = "biz_id";
    String POLICY_ID = "policy_id";
    String BIZ_CURRENT = "biz_current";
    String AVARIABLE = "avariable";

    default void lifeCycleInit(EntityContext context)
    {
        EntityQueryService entityQueryService = context.getBean(EntityQueryService.class);
        Map<String, Object> lifeCycleMap = new HashMap<>(4);
        // TODO 一次查询 获取生命周期相关信息
        lifeCycleMap.put(POLICY_ID, "1001");
        lifeCycleMap.put(AVARIABLE, "1");
        lifeCycleMap.put(BIZ_CURRENT, "init");
        List<AbstractActionEntity> entityList = context.getEntity(this.getClass());
        List<String> idList = new ArrayList<>(entityList.size());
        entityList.forEach(entity -> {
            if (StringUtils.isBlank(entity.getId()))
            {
                entity.setId(UUID.randomUUID().toString());
            }
            idList.add(entity.getId());
            // TODO 生命周期初始化业务
            lifeCycleMap.put(BIZ_ID, UUID.randomUUID().toString());
            entity.setActionProps(lifeCycleMap);

            context.addInsertEntity(entity);
        });

        // TODO 以下代码可能向上抽 比如放到Action中
        if (null != context.getVariable("linkRelation"))
        {
            if ("A".equals(context.getVariable("linkRelation")))
            {
                context.setVariable("roleAObjectId", idList);
            }
            else
            {
                context.setVariable("roleBObjectId", idList);
            }
        }

    }
}
